package mdata

import (
	"fmt"
	"gitee.com/dennis-mxx/gcode-common/mcontext"
	"gitee.com/dennis-mxx/gcode-common/mlogger"
	"xorm.io/xorm/log"
)

type ZapXormLogger struct {
	level   log.LogLevel
	id      string
	showSQL bool
	logger  *mlogger.TraceLogger
}

func NewXormLogger(id string, logger *mlogger.TraceLogger) *ZapXormLogger {
	return &ZapXormLogger{id: id, logger: logger}
}
func (ce *ZapXormLogger) BeforeSQL(ctx log.LogContext) {
}

// AfterSQL implements ContextLogger
func (ce *ZapXormLogger) AfterSQL(ctx log.LogContext) {
	if ce.showSQL {
		mtx := mcontext.WithContext(ctx.Ctx)
		logger := mlogger.WithLogger(mtx.Logger())

		logger.Info("[SQL] ", ctx.SQL)
		if ctx.ExecuteTime == 0 {
			logger.Info("[SQL] args = ", ctx.Args)
		} else {
			logger.Info("[SQL] ", ctx.Args, "  -  ", ctx.ExecuteTime)
		}

	}

}

// Debug empty implementation
func (ce *ZapXormLogger) Debug(v ...interface{}) {
	if ce.level <= log.LOG_DEBUG {
		ce.logger.Debug(v...)
	}
}

// Debugf empty implementation
func (ce *ZapXormLogger) Debugf(format string, v ...interface{}) {
	if ce.level <= log.LOG_DEBUG {
		ce.logger.Debug(fmt.Sprintf(format, v...))
	}
}

// Error empty implementation
func (ce *ZapXormLogger) Error(v ...interface{}) {
	if ce.level <= log.LOG_ERR {
		ce.logger.Error(v...)
	}
}

// Errorf empty implementation
func (ce *ZapXormLogger) Errorf(format string, v ...interface{}) {
	if ce.level <= log.LOG_ERR {
		ce.logger.Error(fmt.Sprintf(format, v...))
	}
}

// Info empty implementation
func (ce *ZapXormLogger) Info(v ...interface{}) {
	if ce.level <= log.LOG_INFO {
		ce.logger.Info(v...)
	}
}

// Infof empty implementation
func (ce *ZapXormLogger) Infof(format string, v ...interface{}) {
	if ce.level <= log.LOG_INFO {
		ce.logger.Info(fmt.Sprintf(format, v...))
	}
}

// Warn empty implementation
func (ce *ZapXormLogger) Warn(v ...interface{}) {
	if ce.level <= log.LOG_WARNING {
		ce.logger.Warn(v...)
	}
}

// Warnf empty implementation
func (ce *ZapXormLogger) Warnf(format string, v ...interface{}) {
	if ce.level <= log.LOG_WARNING {
		ce.logger.Warn(fmt.Sprintf(format, v...))
	}
}

// Level empty implementation
func (ce *ZapXormLogger) Level() log.LogLevel {
	return ce.level
}

// SetLevel empty implementation
func (ce *ZapXormLogger) SetLevel(l log.LogLevel) {
	ce.level = l
}

// ShowSQL empty implementation
func (ce *ZapXormLogger) ShowSQL(show ...bool) {
	if len(show) == 0 {
		ce.showSQL = true
		return
	}
	ce.showSQL = show[0]
}

// IsShowSQL empty implementation
func (ce *ZapXormLogger) IsShowSQL() bool {
	return ce.showSQL
}
